﻿using Biz;
using BusinessLayer.Biz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BusinessLayer.Dal
{
    class UnsoldDal
    {
        DatabaseContext db;
        public UnsoldDal( /* DatabaseContext db */ )
        {
            this.db = DatabaseContext.DB;
        }
        public int GetQuantityByProduct(Product product)
        {
            var unsold = db.Unsolds.Where(u => u.Product.Id == product.Id).OrderByDescending(u=>u.Id).ToList();
            if (unsold.Count>0)
            {
                return unsold.First().QuantityUnsold;
            }
            return 0;
        }
        public List<Unsold> GetList(Product product)
        {
            return db.Unsolds.Where(u => u.Product.Id == product.Id).ToList();
        }
        public TonKho GetByProduct(Product product,DateTime formdate,DateTime todate)
        {
            TonKho tonkho = new TonKho();
            tonkho.product = product;
            if (GetList(product).Count>0)
            {
                List<Unsold> unsolds = db.Unsolds.Where(u => u.Time >= formdate && u.Time <= todate && u.Product.Id==product.Id).ToList();
                if (unsolds.Count <= 0)
                {
                    List<Unsold> un = db.Unsolds.Where(u => u.Time <= formdate && u.Product.Id == product.Id).OrderByDescending(u => u.Id).ToList();
                    if (un.Count > 0)
                    {
                        tonkho.TonDau = tonkho.TonCuoi = un.First().QuantityUnsold;
                    }
                    else
                    {
                        tonkho.TonDau = tonkho.TonCuoi = 0;
                    }
                    tonkho.Nhap = tonkho.Xuat = 0;
                }
                else
                {
                    tonkho.TonDau = unsolds.First().QuantityUnsold - unsolds.First().QuantityImport + unsolds.First().QuantityExport;
                    tonkho.TonCuoi = unsolds.OrderByDescending(u => u.Id).First().QuantityUnsold;
                    tonkho.Nhap = (unsolds.Select(u => u.QuantityImport)).Sum();
                    tonkho.Xuat = (unsolds.Select(u => u.QuantityExport)).Sum();
                }
            }
            else
            {
                tonkho.TonDau = tonkho.TonCuoi = tonkho.Nhap = tonkho.Xuat = 0;
            }
            return tonkho;
        }

        public int Insert(Unsold unsold)
        {
            db.Unsolds.Add(unsold);
            return db.SaveChanges();
        }
    }
}
